//
//  WBNewFeature.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/9.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

class WBNewFeature: UIView {
    
    /// scrollView的懒加载属性
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: self.bounds)
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.contentSize = CGSize(width: screenWidth * 5, height: screenHeight)
        scrollView.delegate = self
        return scrollView
    }()
    
    /// pageControl的懒加载属性
    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.currentPage = 0
        pageControl.numberOfPages = 4
        pageControl.pageIndicatorTintColor = UIColor.black
        pageControl.currentPageIndicatorTintColor = UIColor.orange
        
        return pageControl
    }()
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension WBNewFeature {
    func setupUI () {
        backgroundColor = UIColor.clear
        //1. 添加子视图
        addSubview(scrollView)
        addSubview(pageControl)
        
        //2. 设置scrollView
        let rect = self.bounds
        for i in 1...4 {
            let imageView = UIImageView(imageName: "new_feature_\(i)")
            imageView.frame = rect.offsetBy(dx: screenWidth*CGFloat((i-1)), dy: 0)
            scrollView.addSubview(imageView)
        }
        
        //3. 设置pageControl的位置
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-150)
        }
    }
}

extension WBNewFeature: UIScrollViewDelegate {
    //在scrollView滚动时调用
    func scrollViewDidScroll(_ scrollViewa: UIScrollView) {
        let offset = scrollViewa.contentOffset.x
        //当滚动一半位置时设置pageControl的当前页数
        let currentPage = Int(offset/screenWidth + 0.5)
        pageControl.currentPage = currentPage
        
        //是否隐隐藏pageControl
        pageControl.isHidden = offset > screenWidth * 3.3
        
        //当滑出屏幕，从屏幕移除
        if offset >= screenWidth*4.0 {
            self.removeFromSuperview()
        }
    }
}









